package org.bai.meetingfilm.backend.show.consumer.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @ClassName ConsumerServiceImpl
 * @Description 消费者实现类
 * @Author bai
 * @Date 2021/7/18 15:46
 * @Version 1.0
 **/
@Service
public class ConsumerServiceImpl implements ConsumerService {

    private final RestTemplate restTemplate;
    private final LoadBalancerClient loadBalancerClient;

    @Autowired
    public ConsumerServiceImpl(RestTemplate restTemplate, LoadBalancerClient loadBalancerClient) {
        this.restTemplate = restTemplate;
        this.loadBalancerClient = loadBalancerClient;
    }

    @Override
    public String sayHello(String message) {
        // 请求生产者
        return sayHelloByLoadBalancer(message);
    }

    private String sayHelloByLoadBalancer(String message) {
        ServiceInstance serviceInstance = loadBalancerClient.choose("BACKEND-PROVIDER");
        final String host = serviceInstance.getHost();
        final int port = serviceInstance.getPort();
        final String uri = "/provider/sayHello?message=" + message;
        final String url = "http://" + host + ":" + port + uri;

        String result = restTemplate.getForObject(url, String.class);
        return "请求返回信息: " + result;
    }

    private String sayHelloByHost(String message) {
        final String host = "localhost";
        final int port = 7201;
        final String uri = "/provider/sayHello?message=" + message;
        final String url = "http://" + host + ":" + port + uri;

        String result = restTemplate.getForObject(url, String.class);
        return "请求返回信息: " + result;
    }
}
